package com.woniuxy.productservice.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Snowflake;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.core.model.Result;
import com.woniuxy.core.status.CoachState;
import com.woniuxy.core.status.CourseTypeStateEnum;
import com.woniuxy.core.status.ProductState;
import com.woniuxy.core.status.UserState;
import com.woniuxy.core.util.PageInfo;
import com.woniuxy.productclient.client.CoachFeignClient;
import com.woniuxy.productclient.client.CourseFeignClient;
import com.woniuxy.productclient.client.dto.CoachInfoDto;
import com.woniuxy.productclient.client.dto.CourseTypeDto;
import com.woniuxy.productdao.mapper.TeamProductMapper;
import com.woniuxy.productdao.model.TeamProduct;
import com.woniuxy.productmodel.dto.TeamProductDto;
import com.woniuxy.productmodel.form.AddTeamProductForm;
import com.woniuxy.productmodel.form.ListTeamProductForm;
import com.woniuxy.productmodel.form.UpdateTeamProductForm;
import com.woniuxy.productmodel.form.VenueListTeamProductForm;
import com.woniuxy.productservice.exception.ProductException;
import com.woniuxy.productservice.service.TeamProductService;
import com.woniuxy.util.MyOssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * <p>
 * 团课产品表 服务实现类
 * </p>
 *
 * @author 冉杰
 * @since 2024-01-15
 */
@Service
public class TeamProductServiceImpl extends ServiceImpl<TeamProductMapper, TeamProduct> implements TeamProductService {
    @Autowired
    private CoachFeignClient coachFeignClient;
    @Autowired
    private CourseFeignClient courseFeignClient;
    @Autowired
    private MyOssUtil myOssUtil;
    /**
     *商家端新增团课产品方法
     * @param form
     * @param venueId
     * @return
     */
    @Override
    public TeamProductDto addTeamProduct(AddTeamProductForm form, Integer venueId) throws IOException {
        if (form.getOpenNum()>form.getMaxNum()) throw new ProductException(70001,"开课人数不能大于最大人数");
        //教练前置判断
        Result<CoachInfoDto> res1 = coachFeignClient.findCoachByCoachId(form.getCoachId());
        if (!res1.getFlag()) throw new ProductException(res1.getCode(),res1.getMsg());
        CoachInfoDto coachInfo = res1.getData();
        if (ObjectUtils.isEmpty(coachInfo)) throw new ProductException(50001,"教练不存在");
        if (venueId!=coachInfo.getVenueId()) throw new ProductException(50002,"教练不属于该场馆");
        if(coachInfo.getCoachState()!= CoachState.IS_ENABLE.getState()) throw new ProductException(50005,"教练未启用");
        //课程类别前置判断
        Result<CourseTypeDto> res2 = courseFeignClient.findCourseTypeById(form.getCourseTypeId());
        if (!res2.getFlag()) throw new ProductException(res2.getCode(),res2.getMsg());
        CourseTypeDto courseType = res2.getData();
        if (ObjectUtils.isEmpty(courseType)) throw new ProductException(50006,"该课程类别不存在");
        if (courseType.getCourseTypeState()!= CourseTypeStateEnum.TYPE_ENABLE.getCode()) throw new ProductException(50007,"课程类别未启用");
        TeamProduct teamProduct = BeanUtil.toBean(form, TeamProduct.class);
        teamProduct.setCourseTypeName(courseType.getCourseTypeName());
        teamProduct.setTeamProductState(ProductState.IS_ENABLE.getState());
        teamProduct.setVenueId(venueId);
        save(teamProduct);
        TeamProductDto dto = BeanUtil.toBean(teamProduct, TeamProductDto.class);
        return dto;
    }

    /**
     * 商家端修改团课产品方法
     * @param form
     * @param venueId
     */
    @Override
    public void updateTeamProduct(UpdateTeamProductForm form, Integer venueId) {
        if (form.getOpenNum()>form.getMaxNum()) throw new ProductException(70001,"开课人数不能大于最大人数");
        TeamProduct teamProduct = getById(form.getTeamProductId());
        if (null==teamProduct) throw new ProductException(70002,"产品不存在");
        if (teamProduct.getVenueId()!=venueId) throw new ProductException(70003,"不是该商家产品");
        if (teamProduct.getTeamProductState()==ProductState.IS_OPEN.getState()) throw new ProductException(70003,"产品已开课不能修改");
        //教练前置判断
        Result<CoachInfoDto> res1 = coachFeignClient.findCoachByCoachId(form.getCoachId());
        if (!res1.getFlag()) throw new ProductException(res1.getCode(),res1.getMsg());
        CoachInfoDto coachInfo = res1.getData();
        if (ObjectUtils.isEmpty(coachInfo)) throw new ProductException(50001,"教练不存在");
        if (venueId!=coachInfo.getVenueId()) throw new ProductException(50002,"教练不属于该场馆");
        if(coachInfo.getCoachState()!= CoachState.IS_ENABLE.getState()) throw new ProductException(50005,"教练未启用");
        //课程类别前置判断
        Result<CourseTypeDto> res2 = courseFeignClient.findCourseTypeById(form.getCourseTypeId());
        if (!res2.getFlag()) throw new ProductException(res2.getCode(),res2.getMsg());
        CourseTypeDto courseType = res2.getData();
        if (ObjectUtils.isEmpty(courseType)) throw new ProductException(50006,"该课程类别不存在");
        if (courseType.getCourseTypeState()!= CourseTypeStateEnum.TYPE_ENABLE.getCode()) throw new ProductException(50007,"课程类别未启用");
        teamProduct.setTeamProductName(form.getTeamProductName());
        teamProduct.setTeamProductDesc(form.getTeamProductDesc());
        teamProduct.setCoachId(form.getCoachId());
        teamProduct.setCourseTypeId(form.getCourseTypeId());
        teamProduct.setCourseTypeName(courseType.getCourseTypeName());
        teamProduct.setMaxNum(form.getMaxNum());
        teamProduct.setOpenNum(form.getOpenNum());
        teamProduct.setCourseCount(form.getCourseCount());
        teamProduct.setTeamProductPrice(form.getTeamProductPrice());
        updateById(teamProduct);
    }

    @Override
    public void updateProductImage(MultipartFile updateFile, Integer teamProductId, Integer venueId) throws IOException {
        TeamProduct teamProduct = getById(teamProductId);
        if (null==teamProduct) throw new ProductException(70002,"产品不存在");
        if (teamProduct.getVenueId()!=venueId) throw new ProductException(70003,"不是该商家产品");
        if (teamProduct.getTeamProductState()==ProductState.IS_OPEN.getState()) throw new ProductException(70003,"产品已开课不能修改");
        String type = FileTypeUtil.getType(updateFile.getInputStream());
        if (!type.equals("jpg") && !type.equals("png")) throw new ProductException(70004, "图片格式异常");
        String oldFileName = FileUtil.getName(teamProduct.getTeamProductImage());//保存原文件名
        //先上传新文件，再修改数据库，并把原来的文件删掉
        String fileName = new Snowflake(1, 1).nextIdStr();
        fileName = fileName + "." + type;
        String url = myOssUtil.uploadFile(updateFile.getInputStream(), fileName, "ranjie11");
        //更新数据库
        try {
            teamProduct.setTeamProductImage(url);
            updateById(teamProduct);
        } catch (Exception e) {
            //应该把上传了的文件删掉
            myOssUtil.deleteFile("ranjie11", fileName);
            throw new RuntimeException(e);
        }
        //把原来的文件删除
        if (!ObjectUtils.isEmpty(oldFileName)) myOssUtil.deleteFile("ranjie11", oldFileName);
    }

    /**
     * 根据产品id查找团课产品信息
     * @param teamProductId
     * @return
     */
    @Override
    public TeamProductDto findTeamProductById(Integer teamProductId) {
        TeamProduct teamProduct = getById(teamProductId);
        TeamProductDto dto = BeanUtil.toBean(teamProduct, TeamProductDto.class);
        return dto;
    }

    /**
     * 商家端查看自家团课产品
     * @param form
     * @param venueId
     * @return
     */
    @Override
    public PageInfo<TeamProductDto> venueListTeamProduct(VenueListTeamProductForm form, Integer venueId) {
        Long current = form.getCurrent();
        Long size = form.getSize();
        Page<TeamProduct> page = new Page<>(current == null ? 1l : current, size == null ? 6l : size);
        LambdaQueryWrapper<TeamProduct> wrapper = new LambdaQueryWrapper<TeamProduct>()
                .eq(TeamProduct::getVenueId, venueId)
                .eq(!ObjectUtils.isEmpty(form.getCoachId()), TeamProduct::getCoachId, form.getCoachId())
                .eq(!ObjectUtils.isEmpty(form.getCourseTypeId()), TeamProduct::getCourseTypeId, form.getCourseTypeId())
                .eq(!ObjectUtils.isEmpty(form.getTeamProductState()), TeamProduct::getTeamProductState, form.getTeamProductState())
                .like(!ObjectUtils.isEmpty(form.getTeamProductName()), TeamProduct::getTeamProductName, form.getTeamProductName());
        page(page,wrapper);
        PageInfo<TeamProductDto> pageInfo = BeanUtil.toBean(page, PageInfo.class);
        List<TeamProductDto> list = BeanUtil.copyToList(page.getRecords(), TeamProductDto.class);
        pageInfo.setPages(page.getPages());
        pageInfo.setList(list);
        return pageInfo;
    }

    /**
     * 用户端查看团课产品信息
     * @param form
     * @return
     */
    @Override
    public PageInfo<TeamProductDto> listTeamProduct(ListTeamProductForm form) {
        Long current = form.getCurrent();
        Long size = form.getSize();
        Page<TeamProduct> page = new Page<>(current == null ? 1l : current, size == null ? 6l : size);
        LambdaQueryWrapper<TeamProduct> wrapper = new LambdaQueryWrapper<TeamProduct>()
                .eq(TeamProduct::getVenueId, form.getVenueId())
                .eq(!ObjectUtils.isEmpty(form.getCoachId()), TeamProduct::getCoachId, form.getCoachId())
                .eq(!ObjectUtils.isEmpty(form.getCourseTypeId()), TeamProduct::getCourseTypeId, form.getCourseTypeId())
                .like(!ObjectUtils.isEmpty(form.getTeamProductName()), TeamProduct::getTeamProductName, form.getTeamProductName());
        page(page,wrapper);
        PageInfo<TeamProductDto> pageInfo = BeanUtil.toBean(page, PageInfo.class);
        List<TeamProductDto> list = BeanUtil.copyToList(page.getRecords(), TeamProductDto.class);
        pageInfo.setPages(page.getPages());
        pageInfo.setList(list);
        return pageInfo;
    }

    /**
     * 商家端端启用团课产品
     * @param teamProductId
     * @param venueId
     */
    @Override
    public void enableTeamProduct(Integer teamProductId, Integer venueId) {
        TeamProduct teamProduct = getById(teamProductId);
        if (null==teamProduct) throw new ProductException(70001,"产品不存在");
        if (teamProduct.getVenueId()!=venueId) throw new ProductException(70002,"不是该商家的产品");
        if (teamProduct.getTeamProductState()==ProductState.IS_ENABLE.getState()||
        teamProduct.getTeamProductState()==ProductState.IS_OPEN.getState()) throw new ProductException(70003,"商家已启用产品，重复操作");
        teamProduct.setTeamProductState(ProductState.IS_ENABLE.getState());
        updateById(teamProduct);
    }

    /**
     * 商家端禁用团课产品
     * @param teamProductId
     * @param venueId
     */
    @Override
    public void disabledTeamProduct(Integer teamProductId, Integer venueId) {
        TeamProduct teamProduct = getById(teamProductId);
        if (null==teamProduct) throw new ProductException(70001,"产品不存在");
        if (teamProduct.getVenueId()!=venueId) throw new ProductException(70002,"不是该商家的产品");
        if (teamProduct.getTeamProductState()==ProductState.IS_DISABLED.getState())
            throw new ProductException(70004,"产品已禁用,重复操作");
        if (teamProduct.getTeamProductState()== ProductState.IS_OPEN.getState())
            throw new ProductException(70005,"该团课产品已开课，无法禁用");
        teamProduct.setTeamProductState(ProductState.IS_DISABLED.getState());
        updateById(teamProduct);
    }

}
